package com.android.calldelay;

import java.lang.reflect.Method;
import java.util.Calendar;

import com.android.calldelay.receiver.OnCallDisconnectReceave;
import com.android.internal.telephony.ITelephony;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Handler;
import android.os.RemoteException;
import android.os.StrictMode;
import android.support.v4.app.NotificationCompat.Action;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.widget.Toast;

public class OnAlarmReceive extends BroadcastReceiver {

	private static final String LOG_TAG = "OnAlarmReceive";
	private Context context;

	@Override
	public void onReceive(Context context, Intent intent) {
		// calling for initiating the call delay
		this.context = context;

		/*String callNumber = intent.getExtras().getString(
				MainActivity.CALL_DELAYED_FIRST_NUMBER);*/
		
		
		String firstNumber = getStringData(AppInfo.KEY_FIRST_NUMBER_KEY);
		Intent callIntent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:"
				+ firstNumber));
		callIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		AppInfo.FLAG_CALL_IS_DISCONNECTED = false;
		context.startActivity(callIntent);
		 
		setUpAlarmForDisconnect();
		Log.d(LOG_TAG, "first call is started......."+AppInfo.FLAG_CALL_IS_DISCONNECTED);
		AppInfo.FLAG_ALARM_START = true;

	}




	private void setUpAlarmForDisconnect() {
		


		AlarmManager alarmManager = (AlarmManager)context. getSystemService(Context.ALARM_SERVICE);
		Intent intent = new Intent(context, OnCallDisconnectReceave.class);

		PendingIntent pendingIntent = PendingIntent
				.getBroadcast(context, 0, intent,
						PendingIntent.FLAG_UPDATE_CURRENT);
		// retriving the seconds 
		int secondsBeforeDialingAgain = context.getSharedPreferences(AppInfo.APP_PREF, 1)
				.getInt(AppInfo.KEY_SECONDS_BEFORE_DIALING_AGAIN,1);
	//	Toast.makeText(context, "secondsBeforeDialingAgain  in calling first number... "+secondsBeforeDialingAgain, Toast.LENGTH_SHORT).show();


		// Getting current time and add the seconds in it
		Calendar cal = Calendar.getInstance();
		cal.add(Calendar.SECOND, secondsBeforeDialingAgain);
		alarmManager.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(),
				pendingIntent);


	}

	// getting the string data from preferences
		private String getStringData(String key) {
			SharedPreferences setting = context.getSharedPreferences(AppInfo.APP_PREF,
					0);
			return setting.getString(key, "");
		}


}
